/*
 * SessionManager.cpp
 *
 *  Created on: Sep 13, 2012
 *      Author: shawnmao
 */

#include "SessionManager.h"
#include "pthread_function.h"

int SessionManager::add_srv_session(uint8_t index,
		                 	 	 	TcpServerSession* srv_session_ptr)
{
	pair<pthread_t, TcpServerSession*> srv_pid_pair(0, srv_session_ptr);
	pair< uint8_t, pair<pthread_t, TcpServerSession*> > srv_pair(index, srv_pid_pair);
	m_srv_session_map.insert(srv_pair);

	return 0;
}

int SessionManager::add_cli_session(uint8_t index,
									TcpClientSession* cli_session_ptr)
{
	pair<pthread_t, TcpClientSession*> cli_pid_pair(0, cli_session_ptr);
	pair< uint8_t, pair<pthread_t, TcpClientSession*> > cli_pair(index, cli_pid_pair);
	m_cli_session_map.insert(cli_pair);

	return 0;
}

int SessionManager::start_srv_session(uint8_t index)
{
	pthread_t tid;
	int ret_val;
	map< uint8_t, pair<pthread_t, TcpServerSession*> >::iterator it_srv
												= m_srv_session_map.find(index);
	if(m_srv_session_map.end() != it_srv) {
		ret_val = pthread_create(&tid, NULL, create_tcp_srv_listen_thread, it_srv->second.second);
		if(0 != ret_val) {
			cout<<"Fail to create a thread for tcp server listenning session, "
					"the failure reason is: "<<errno<<endl;
			return -1;
		}

		ret_val = pthread_detach(tid);
		if(0 != ret_val) {
			cout<<"Fail to detach the new created thread, "
					"the failure reason is: "<<errno<<endl;
			return -1;
		}

		it_srv->second.first = tid;
	}

	return 0;
}

int SessionManager::start_cli_session(uint8_t index)
{
	pthread_t tid;
	int ret_val;
	map< uint8_t, pair<pthread_t, TcpClientSession*> >::iterator it_cli
												= m_cli_session_map.find(index);
	if(m_cli_session_map.end() != it_cli) {
		ret_val = pthread_create(&tid, NULL, create_tcp_cli_thread, it_cli->second.second);
		if(0 != ret_val) {
			cout<<"Fail to create a thread for tcp client session, "
					"the failure reason is: "<<errno<<endl;
			return -1;
		}

		ret_val = pthread_detach(tid);
		if(0 != ret_val) {
			cout<<"Fail to detach the new created thread, "
					"the failure reason is: "<<errno<<endl;
			return -1;
		}

		it_cli->second.first = tid;
	}

	return 0;
}

int SessionManager::close_srv_session(uint8_t index)
{

}

int SessionManager::close_cli_session(uint8_t index)
{

}

